const express = require('express');
const router = express.Router();
const Resident = require('../models/Resident');

// 获取所有老人信息
router.get('/residents', async (req, res) => {
    try {
        const residents = await Resident.findAll();
        res.json({
            success: true,
            data: residents
        });
    } catch (error) {
        res.status(500).json({
            success: false,
            message: error.message
        });
    }
});

// 添加新老人信息
router.post('/add-resident', async (req, res) => {
    try {
        const resident = await Resident.create(req.body);
        res.status(201).json({
            success: true,
            data: resident
        });
    } catch (error) {
        res.status(400).json({
            success: false,
            message: error.message
        });
    }
});

// 更新老人信息
router.put('/update-resident/:id', async (req, res) => {
    try {
        const [updated] = await Resident.update(req.body, {
            where: { id: req.params.id }
        });
        if (updated) {
            const updatedResident = await Resident.findByPk(req.params.id);
            res.json({
                success: true,
                data: updatedResident
            });
        } else {
            res.status(404).json({
                success: false,
                message: '未找到该老人信息'
            });
        }
    } catch (error) {
        res.status(400).json({
            success: false,
            message: error.message
        });
    }
});

// 删除老人信息
router.delete('/delete-resident/:id', async (req, res) => {
    try {
        const deleted = await Resident.destroy({
            where: { id: req.params.id }
        });
        if (deleted) {
            res.json({
                success: true,
                message: '删除成功'
            });
        } else {
            res.status(404).json({
                success: false,
                message: '未找到该老人信息'
            });
        }
    } catch (error) {
        res.status(400).json({
            success: false,
            message: error.message
        });
    }
});

module.exports = router; 